﻿using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System.Threading;

namespace LogDemo
{
    public class Job1 : IHostedService,IDisposable
    {
        private readonly ILogger logger;
        public Job1(ILogger<Job1> logger)
        {
            this.logger= logger;
        }

        private CancellationTokenSource? cancellationToken;

        public async Task StartAsync(CancellationToken stoppingToken)
        {
            logger.LogInformation("{Service} is running.jsonTest:{{\"name\":\"admin\"}}", nameof(Job1));

            cancellationToken = new();
            DoWork(cancellationToken.Token);
            await Task.CompletedTask;
        }

        private void DoWork(CancellationToken stoppingToken)
        {
            Task.Run(() =>
            {
                int count = 0;
                while (stoppingToken.IsCancellationRequested == false)
                {
                    count++;
                    logger.LogInformation($"working,execution count:{count}");
                    Task.Delay(1000).Wait();
                }
            }, stoppingToken);
        }

        public Task StopAsync(CancellationToken stoppingToken)
        {
            logger.LogInformation("{Service} is stopping.", nameof(Job1));

            cancellationToken.Cancel();

            return Task.CompletedTask;
        }

        public void Dispose()
        {
            if (cancellationToken?.IsCancellationRequested==false)
            {
                cancellationToken.Cancel();
            }
        }
    }
}
